class AppError extends Error {
    constructor(message, statusCode = 400) {
        super(message);
        this.statusCode = statusCode;
        this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
        this.isOperational = true;

        Error.captureStackTrace(this, this.constructor);
    }
}

const handleValidationError = (err) => {
    const errors = Object.values(err.errors).map(error => error.message);
    return new AppError(`输入验证失败: ${errors.join('. ')}`, 400);
};

const handleDuplicateFieldsError = (err) => {
    const value = err.errmsg.match(/(["'])(\\?.)*?\1/)[0];
    return new AppError(`重复的字段值: ${value}。请使用其他值！`, 400);
};

const handleJWTError = () => new AppError('无效的令牌，请重新登录！', 401);

const handleJWTExpiredError = () => new AppError('令牌已过期，请重新登录！', 401);

module.exports = {
    AppError,
    handleValidationError,
    handleDuplicateFieldsError,
    handleJWTError,
    handleJWTExpiredError
};